<template>
  <div>
    <el-card class="login" shadow="always" :body-style="{ padding: '20px' }">
      <div slot="header">
        <span>请登录</span>
      </div>
      <el-form
        :model="form"
        ref="loginRef"
        :rules="rules"
        label-width="80px"
        :inline="false"
        size="normal"
      >
        <el-form-item label="用户名" prop="account">
          <el-input v-model="form.account"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="login" :loading="loading"
            >登录</el-button
          >
          <el-button @click="register">注册</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>
<script>
export default {
  data: () => ({
    form: {
      account: '',
      password: ''
    },
    loading: false,
    rules: {
      account: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 3, max: 16, message: '长度在 3 到 16 个字符', trigger: 'blur' }
      ]
    }
  }),
  methods: {
    login() {
      this.$refs.loginRef.validate((valid) => {
        if (valid) {
          this.loading = true
          this.$store
            .dispatch('users/login', this.form)
            .then(() => {
              this.loading = false
              this.$router.push('/main')
            })
            .catch((err) => {
              console.log(err)
              this.loading = false
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    register() {
      this.$router.push('./register')
    }
  }
}
</script>
<style lang="scss" scoped>
.login {
  width: 500px;
  margin: 150px auto;
}
</style>